package com.jiangzhuolin.admin.config;

import com.jiangzhuolin.admin.util.MyPasswordEncoder;
import com.jiangzhuolin.admin.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userService;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    /**
     * 配置 Spring Security 忽略静态文件的认证
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
    }

    /**
     * 配置 Spring Security HTTP 认证规则
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers().frameOptions().disable()
                .and()
                .authorizeRequests()
                .antMatchers("/").permitAll()   // 允许根路径无需认证的直接访问
                .antMatchers("/registry").permitAll() // 注册请求不需要验证
//                .antMatchers("/adminRole").hasRole("ADMIN") // 只有拥有 ADMIN 角色的用户才能使用
                .anyRequest().authenticated()   // 其他所有路径都需要认证
                .and()
                .logout().permitAll()   // 允许注销无需认证
                .and()
                .formLogin();   // 允许表单登录的认证
        // 关闭 csrf
        http.csrf().disable();
    }

    /**
     * 配置 Spring Security 的认证信息（用户/密码/角色...）
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 基于数据库存储的用户信息
        auth.userDetailsService(userService).passwordEncoder(myPasswordEncoder);
    }
}
